package main

import (
	"github.com/julienschmidt/httprouter"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"
)

func testPageHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	t, _ := template.ParseFiles(VIDEO_DIR + "upload.html")
	t.Execute(w, nil) //模板引擎解析一个html文件，然后通过w渲染到前端
}

func streamHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	vid := p.ByName("vid-id")
	vl := VIDEO_DIR + vid //videoLinks
	video, err := os.Open(vl)
	log.Printf("你现在访问的vid: %s,访问路径：%s,返回video : %v", vid, vl, video)
	if err != nil {
		sendErrorResponse(w, http.StatusInternalServerError, "Internal error")
		return
	}
	w.Header().Set("Content-Type", "video/mp4")
	http.ServeContent(w, r, "", time.Now(), video)
	//关键是通过ServeContent函数将文件作为二进制流通过write进行写出传输
	defer video.Close()
}

func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	log.Println("uploadHandler is running...")
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
	if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
		//校验文件大小
		sendErrorResponse(w, http.StatusBadRequest, "File is too big.")
		return
	}
	//现在body已经正确取出来了，下面进行读取到服务器中的流程
	file, _, err := r.FormFile("file")
	if err != nil {
		log.Printf("Error when try to open file: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal error.")
		return
	}
	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Printf("read file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal error.")
	}
	fn := p.ByName("vid-id")
	err = ioutil.WriteFile(VIDEO_DIR+fn, data, 0666)
	if err != nil {
		log.Printf("write file error : %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal error.")
		return
	}
	w.WriteHeader(http.StatusCreated)
	io.WriteString(w, "Uploaded successfully.")
}
